import axios from "axios";
import Element from 'element-ui'
import router from '@/router'

const myaxios = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
})

// myaxios.defaults.baseURL = 

myaxios.interceptors.request.use(config => {
    config.headers['token'] = localStorage.getItem('token')
    return config
})

myaxios.interceptors.response.use(response => {
        let result = response.data
        if (result.code == 200) {
            return response
        } else {
            Element.Message.warning(result.message ? result.message : '系统异常');
            return Promise.reject(response.data.message)
        }
    },
    error => {
        if (error.response.data) {
            error.message = error.response.data.message
        }
        if (error.response.status == 401) {
            router.push('/login')
            return Promise.reject(error)
        }
        if (error.response.status == 404) {
            router.push('/notfound')
            return Promise.reject(error)
        }
        if (error.response.status == 400) {
            error.message = '请求服务器的方法错误'
        }
        if (error.response.status == 500) {
            error.message = '服务器代码错误'
        }
        Element.Message.error(error.message)
        return Promise.reject(error)
    }
)

export default myaxios